<template>
  <div class="p-6 space-y-6">
    <!-- 页面标题 -->
    <div class="text-center mb-8">
      <h1 class="text-4xl font-bold text-white mb-2 animate-glow flex items-center justify-center">
        <FileText class="w-10 h-10 mr-4 text-blue-400" />
        {{ ts('政策中心', '政策中心') }}
      </h1>
      <p class="text-blue-400">{{ ts('政策分析、查询、对比、推演一站式服务平台', '政策分析、查询、对比、推演一站式服务平台') }}</p>
    </div>

    <!-- 功能导航卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
      <div v-for="feature in features" :key="feature.id" @click="switchTab(feature.id)" :class="[
        'glass-card p-6 cursor-pointer transition-all duration-300 group',
        activeTab === feature.id ? 'cyber-glow border-blue-500' : 'hover:cyber-glow'
      ]">
        <div class="text-center space-y-3">
          <div :class="[
            'w-20 h-20 mx-auto rounded-full flex items-center justify-center transition-all',
            activeTab === feature.id ? 'bg-blue-500' : 'bg-blue-500/20 group-hover:bg-blue-500/40'
          ]">
            <component :is="feature.icon" :class="[
              'w-10 h-10',
              activeTab === feature.id ? 'text-white' : 'text-blue-500'
            ]" />
          </div>
          <h3 :class="[
            'text-lg font-semibold transition-colors',
            activeTab === feature.id ? 'text-blue-500' : 'text-white group-hover:text-blue-500'
          ]">
            {{ ts(feature.title, feature.title) }}
          </h3>
          <p class="text-blue-400 text-sm">{{ ts(feature.description, feature.description) }}</p>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="glass-card p-8">
      <!-- 智能分析标签页 -->
      <div v-if="activeTab === 'analysis'" class="space-y-6">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-white flex items-center">
            <Target class="w-6 h-6 mr-3 text-blue-500" />
            {{ ts('智能政策分析', '智能政策分析') }}
          </h2>
          <button @click="startAnalysis" :disabled="isAnalyzing"
            class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50">
            {{ isAnalyzing ? ts('分析中...', '分析中...') : ts('开始分析', '开始分析') }}
          </button>
        </div>

        <!-- 分析参数设置 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div class="lg:col-span-2 space-y-4">
            <div>
              <label class="block text-white font-medium mb-2">{{ ts('选择分析维度', '选择分析维度') }}</label>
              <div class="grid grid-cols-2 gap-3">
                <label v-for="dimension in analysisDimensions" :key="dimension.id" class="flex items-center space-x-2">
                  <input type="checkbox" v-model="selectedDimensions" :value="dimension.id"
                    class="w-4 h-4 text-blue-500 rounded focus:ring-blue-500">
                  <span class="text-white text-sm">{{ ts(dimension.name, dimension.name) }}</span>
                </label>
              </div>
            </div>

            <div>
              <label class="block text-white font-medium mb-2">{{ ts('目标地区', '目标地区') }}</label>
              <select v-model="selectedRegion"
                class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600">
                <option value="">{{ ts('选择地区', '选择地区') }}</option>
                <option v-for="region in regions" :key="region.code" :value="region.code">
                  {{ ts(region.name, region.name) }}
                </option>
              </select>
            </div>

            <div>
              <label class="block text-white font-medium mb-2">{{ ts('政策关键词', '政策关键词') }}</label>
              <input v-model="analysisKeywords" type="text" placeholder="输入政策相关关键词，用逗号分隔"
                class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600 placeholder-gray-400">
            </div>
          </div>

          <!-- 分析结果预览 -->
          <div class="bg-white/5 rounded-lg p-4">
            <h4 class="text-white font-medium mb-3">{{ ts('快速洞察', '快速洞察') }}</h4>
            <div class="space-y-3">
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('匹配政策数', '匹配政策数') }}</span>
                <span class="text-blue-500 font-bold">{{ analysisStats.matchedPolicies }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('关联度评分', '关联度评分') }}</span>
                <span class="text-green-400 font-bold">{{ analysisStats.relevanceScore }}%</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('预期收益', '预期收益') }}</span>
                <span class="text-yellow-400 font-bold">{{ analysisStats.expectedBenefit }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分析结果展示 -->
        <div v-if="analysisResults.length > 0" class="mt-8">
          <h3 class="text-xl font-bold text-white mb-4">{{ ts('分析结果', '分析结果') }}</h3>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div v-for="result in analysisResults" :key="result.id"
              class="bg-white/5 rounded-lg p-6 border border-blue-500/30">
              <div class="flex items-start justify-between mb-3">
                <h4 class="text-white font-medium">{{ ts(result.title, result.title) }}</h4>
                <span :class="[
                  'text-xs px-2 py-1 rounded',
                  result.priority === 'high' ? 'bg-red-500/20 text-red-400' :
                    result.priority === 'medium' ? 'bg-yellow-500/20 text-yellow-400' :
                      'bg-green-500/20 text-green-400'
                ]">
                  {{ ts(result.priorityText, result.priorityText) }}
                </span>
              </div>
              <p class="text-blue-400 text-sm mb-4">{{ ts(result.description, result.description) }}</p>
              <div class="flex items-center justify-between">
                <span class="text-blue-500 text-sm font-medium">{{ ts(result.benefit, result.benefit) }}</span>
                <button class="text-blue-500 hover:text-blue-400 text-sm">{{ ts('查看详情', '查看详情') }}</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 政策查询标签页 -->
      <div v-if="activeTab === 'search'" class="space-y-6">
        <PolicyQuery />
      </div>

      <!-- 政策对比标签页 -->
      <div v-if="activeTab === 'compare'" class="space-y-6">
        <PolicyCompare />
      </div>

      <!-- 政策溯源标签页 -->
      <div v-if="activeTab === 'trace'" class="space-y-6">
        <PolicySource />
      </div>

      <!-- 税收分析标签页 -->
      <div v-if="activeTab === 'tax-analysis'" class="space-y-6">
        <TaxPolicyAnalysisAgent />
      </div>

      <!-- 政策推演标签页 -->
      <div v-if="activeTab === 'simulation'" class="space-y-6">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-2xl font-bold text-white flex items-center">
            <Brain class="w-6 h-6 mr-3 text-blue-500" />
            {{ ts('政策推演', '政策推演') }}
          </h2>
          <button @click="startSimulation" :disabled="isSimulating"
            class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50">
            {{ isSimulating ? ts('推演中...', '推演中...') : ts('开始推演', '开始推演') }}
          </button>
        </div>

        <!-- 推演参数设置 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div class="lg:col-span-2 space-y-6">
            <div>
              <h3 class="text-lg font-semibold text-white mb-4">{{ ts('推演场景设置', '推演场景设置') }}</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-white font-medium mb-2">{{ ts('政策类型', '政策类型') }}</label>
                  <select v-model="simulationParams.policyType"
                    class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600">
                    <option value="tax">{{ ts('税收政策', '税收政策') }}</option>
                    <option value="trade">{{ ts('贸易政策', '贸易政策') }}</option>
                    <option value="investment">{{ ts('投资政策', '投资政策') }}</option>
                  </select>
                </div>

                <div>
                  <label class="block text-white font-medium mb-2">{{ ts('推演时长', '推演时长') }}</label>
                  <select v-model="simulationParams.duration"
                    class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600">
                    <option value="6months">{{ ts('6个月', '6个月') }}</option>
                    <option value="1year">{{ ts('1年', '1年') }}</option>
                    <option value="3years">{{ ts('3年', '3年') }}</option>
                    <option value="5years">{{ ts('5年', '5年') }}</option>
                  </select>
                </div>

                <div>
                  <label class="block text-white font-medium mb-2">{{ ts('影响范围', '影响范围') }}</label>
                  <select v-model="simulationParams.scope"
                    class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600">
                    <option value="local">{{ ts('地方级', '地方级') }}</option>
                    <option value="national">{{ ts('国家级', '国家级') }}</option>
                    <option value="international">{{ ts('国际级', '国际级') }}</option>
                  </select>
                </div>

                <div>
                  <label class="block text-white font-medium mb-2">{{ ts('经济模型', '经济模型') }}</label>
                  <select v-model="simulationParams.model"
                    class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600">
                    <option value="conservative">{{ ts('保守模型', '保守模型') }}</option>
                    <option value="moderate">{{ ts('中性模型', '中性模型') }}</option>
                    <option value="aggressive">{{ ts('激进模型', '激进模型') }}</option>
                  </select>
                </div>
              </div>
            </div>

            <div>
              <label class="block text-white font-medium mb-2">{{ ts('政策描述', '政策描述') }}</label>
              <textarea v-model="simulationParams.description" placeholder="详细描述要推演的政策内容..." rows="4"
                class="w-full p-3 bg-gray-800 text-white rounded-lg border border-gray-600 placeholder-gray-400"></textarea>
            </div>
          </div>

          <!-- 推演预览 -->
          <div class="bg-white/5 rounded-lg p-4">
            <h4 class="text-white font-medium mb-3">{{ ts('推演概览', '推演概览') }}</h4>
            <div class="space-y-3">
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('推演复杂度', '推演复杂度') }}</span>
                <span class="text-yellow-400 font-bold">{{ simulationComplexity }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('预计时间', '预计时间') }}</span>
                <span class="text-blue-400 font-bold">{{ estimatedTime }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400 text-sm">{{ ts('可信度', '可信度') }}</span>
                <span class="text-green-400 font-bold">{{ credibilityScore }}%</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 推演结果 -->
        <div v-if="simulationResults.length > 0" class="mt-8">
          <h3 class="text-xl font-bold text-white mb-6">{{ ts('推演结果', '推演结果') }}</h3>
          <div class="space-y-6">
            <div v-for="result in simulationResults" :key="result.id"
              class="bg-white/5 rounded-lg p-6 border border-blue-500/30">
              <div class="flex items-center justify-between mb-4">
                <h4 class="text-white font-medium text-lg">{{ ts(result.phase, result.phase) }}</h4>
                <span class="text-blue-500 text-sm">{{ result.timeframe }}</span>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div class="text-center">
                  <div class="text-2xl font-bold text-green-400 mb-1">{{ result.positiveImpact }}%</div>
                  <div class="text-gray-400 text-sm">{{ ts('正面影响', '正面影响') }}</div>
                </div>
                <div class="text-center">
                  <div class="text-2xl font-bold text-red-400 mb-1">{{ result.negativeImpact }}%</div>
                  <div class="text-gray-400 text-sm">{{ ts('负面影响', '负面影响') }}</div>
                </div>
                <div class="text-center">
                  <div class="text-2xl font-bold text-blue-400 mb-1">{{ result.uncertainty }}%</div>
                  <div class="text-gray-400 text-sm">{{ ts('不确定性', '不确定性') }}</div>
                </div>
              </div>

              <p class="text-white/70 text-sm">{{ ts(result.description, result.description) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PolicyQuery from './PolicyQuery.vue'
import PolicyCompare from '../components/PolicyCompare.vue'
import PolicyTrace from './PolicyTrace.vue'
import PolicySource from './PolicySource.vue'
import TaxPolicyAnalysisAgent from './TaxPolicyAnalysisAgent.vue'
import { themeState } from '../services/themeService.js'
import { useTranslation } from '../composables/useTranslation.js'
import MarkdownIt from 'markdown-it'
import {
  FileText,
  Target,
  Search,
  BarChart3,
  Brain,
  BookmarkPlus,
  Share,
  Download,
  Copy,
  X,
  GitCompare,
  Calculator,
  FileText as FileTextIcon,
  File,
} from 'lucide-vue-next'

export default {
  name: 'PolicyCenter',
  components: {
    FileText,
    Target,
    Search,
    BarChart3,
    Brain,
    BookmarkPlus,
    Share,
    Download,
    Copy,
    X,
    GitCompare,
    FileTextIcon,
    File,
    PolicyQuery,
    PolicyCompare,
    PolicyTrace,
    Calculator,
    TaxPolicyAnalysisAgent,
    PolicySource,
  },

  setup() {
    const { ts } = useTranslation()
    const route = useRoute()
    const router = useRouter()

    // 从URL参数初始化activeTab，默认为'analysis'
    const activeTab = ref(route.query.tab || 'analysis')
    const isAnalyzing = ref(false)
    const isSimulating = ref(false)
    const searchQuery = ref('')
    const analysisKeywords = ref('')
    const selectedRegion = ref('')
    const selectedDimensions = ref([])

    // 功能模块定义
    const features = [
      {
        id: 'analysis',
        title: '智能分析',
        description: 'AI驱动的政策深度分析',
        icon: 'Target'
      },
      {
        id: 'search',
        title: '政策查询',
        description: '全球政策数据库搜索',
        icon: 'Search'
      },
      {
        id: 'compare',
        title: '对比分析',
        description: '多维度政策对比',
        icon: 'BarChart3'
      },
      {
        id: 'simulation',
        title: '政策推演',
        description: 'AI政策影响预测',
        icon: 'Brain'
      },
      {
        id: 'tax-analysis',
        title: '税收分析',
        description: '智能税收政策对比分析',
        icon: 'Calculator'
      },
      {
        id: 'trace',
        title: '政策溯源',
        description: '追踪政策历史沿革',
        icon: 'FileText'
      },
    ]

    // 模拟数据
    const analysisDimensions = [
      { id: 'economic', name: '经济影响' },
      { id: 'social', name: '社会影响' },
      { id: 'environmental', name: '环境影响' },
      { id: 'legal', name: '法律影响' },
      { id: 'international', name: '国际影响' },
      { id: 'industry', name: '行业影响' }
    ]

    const regions = [
      { code: 'china', name: '中国' },
      { code: 'usa', name: '美国' },
      { code: 'eu', name: '欧盟' },
      { code: 'asean', name: '东盟' },
      { code: 'japan', name: '日本' },
      { code: 'korea', name: '韩国' }
    ]

    const analysisStats = ref({
      matchedPolicies: 1247,
      relevanceScore: 94,
      expectedBenefit: '高',
      processingTime: '2.3秒',
      dataConfidence: '96%'
    })

    const analysisResults = ref([])
    const searchResults = ref([])
    const simulationResults = ref([])

    const searchFilters = ref({
      category: '',
      region: '',
      status: '',
      sortBy: 'relevance'
    })

    const simulationParams = ref({
      policyType: 'tax',
      duration: '1year',
      scope: 'national',
      model: 'moderate',
      description: ''
    })

    // 计算属性
    const simulationComplexity = computed(() => {
      const params = simulationParams.value
      let complexity = 'LOW'

      if (params.scope === 'international' || params.duration === '5years') {
        complexity = 'HIGH'
      } else if (params.scope === 'national' || params.duration === '3years') {
        complexity = 'MEDIUM'
      }

      return complexity
    })

    const estimatedTime = computed(() => {
      const complexity = simulationComplexity.value
      if (complexity === 'HIGH') return '15-20分钟'
      if (complexity === 'MEDIUM') return '8-12分钟'
      return '3-5分钟'
    })

    const credibilityScore = computed(() => {
      const params = simulationParams.value
      let score = 85

      if (params.model === 'conservative') score += 10
      if (params.scope === 'local') score += 5
      if (params.duration === '6months') score += 5

      return Math.min(score, 98)
    })

    // 方法
    const startAnalysis = async () => {
      isAnalyzing.value = true
      try {
        // 调用后端AI分析API，传递分析参数
        const res = await axios.post('/api/ai/policy/compare', {
          keywords: analysisKeywords.value,
          region: selectedRegion.value,
          dimensions: selectedDimensions.value
        });
        analysisResults.value = res.data && res.data.results ? res.data.results : [];
      } catch (e) {
        analysisResults.value = [];
        console.error('智能分析失败', e);
      }
      isAnalyzing.value = false
    }

    const performSearch = () => {
      // 模拟搜索
      searchResults.value = [
        {
          id: 1,
          title: '跨境电商零售进口商品清单管理办法',
          category: '贸易政策',
          region: '中国',
          publishDate: '2024-01-15',
          status: 'active',
          statusText: '生效中',
          summary: '规范跨境电商零售进口商品清单管理，明确商品准入标准和监管要求，新增1413项商品',
          impact: 85,
          relevance: 92,
          tags: ['跨境电商', '进口清单', '零售'],
          department: '商务部',
          effectiveDate: '2024-03-01'
        },
        {
          id: 2,
          title: 'RCEP原产地累积规则实施指南',
          category: '贸易政策',
          region: 'RCEP',
          publishDate: '2024-02-01',
          status: 'active',
          statusText: '生效中',
          summary: 'RCEP协议原产地累积规则详细实施指南，帮助企业充分利用关税优惠',
          impact: 90,
          relevance: 95,
          tags: ['RCEP', '原产地', '关税优惠'],
          department: '海关总署',
          effectiveDate: '2024-01-01'
        },
        {
          id: 3,
          title: '外商投资法实施条例（2024年修订）',
          category: '投资政策',
          region: '中国',
          publishDate: '2024-02-01',
          status: 'active',
          statusText: '生效中',
          summary: '进一步放宽外商投资准入限制，优化外商投资环境，新增服务业开放措施',
          impact: 78,
          relevance: 87,
          tags: ['外商投资', '准入限制', '负面清单'],
          department: '国家发改委',
          effectiveDate: '2024-03-15'
        },
        {
          id: 4,
          title: '一带一路沿线国家投资合作优惠政策汇编',
          category: '投资政策',
          region: '一带一路',
          publishDate: '2024-01-20',
          status: 'active',
          statusText: '生效中',
          summary: '汇总一带一路沿线65个国家的投资优惠政策，涵盖基础设施、能源、数字经济等领域',
          impact: 82,
          relevance: 88,
          tags: ['一带一路', '投资合作', '基础设施'],
          department: '国家发改委',
          effectiveDate: '2024-02-01'
        },
        {
          id: 5,
          title: '欧盟碳边境调节机制(CBAM)实施细则',
          category: '环保政策',
          region: '欧盟',
          publishDate: '2024-01-10',
          status: 'active',
          statusText: '生效中',
          summary: 'CBAM正式实施细则，涵盖水泥、钢铁、铝、化肥、电力和氢气等行业',
          impact: 88,
          relevance: 91,
          tags: ['碳边境', 'CBAM', '环保'],
          department: '欧盟委员会',
          effectiveDate: '2024-01-01'
        },
        {
          id: 6,
          title: '美国通胀削减法案(IRA)清洁能源税收抵免指南',
          category: '税收政策',
          region: '美国',
          publishDate: '2024-01-05',
          status: 'active',
          statusText: '生效中',
          summary: 'IRA清洁能源投资和生产税收抵免详细指南，包括太阳能、风能、储能等技术',
          impact: 85,
          relevance: 89,
          tags: ['IRA', '清洁能源', '税收抵免'],
          department: '美国财政部',
          effectiveDate: '2024-01-01'
        }
      ]
    }

    const startSimulation = async () => {
      isSimulating.value = true
      try {
        // 调用后端AI推演API，传递推演参数
        const res = await axios.post('/api/ai/policy/simulation', simulationParams.value);
        simulationResults.value = res.data && res.data.results ? res.data.results : [];
      } catch (e) {
        simulationResults.value = [];
        console.error('政策推演失败', e);
      }
      isSimulating.value = false
    }

    const exportResults = () => {
      console.log('导出搜索结果')
    }

    // 切换标签页并更新URL
    const switchTab = (tabId) => {
      activeTab.value = tabId
      // 更新URL参数但不触发页面刷新
      router.push({
        path: '/policy-center',
        query: { tab: tabId }
      })
    }

    // 监听路由变化，当URL参数改变时同步更新activeTab
    watch(
      () => route.query.tab,
      (newTab) => {
        if (newTab && newTab !== activeTab.value) {
          activeTab.value = newTab
        }
      }
    )

    // 页面挂载时，确保URL和activeTab同步
    onMounted(() => {
      if (route.query.tab && route.query.tab !== activeTab.value) {
        activeTab.value = route.query.tab
      }
    })

    return {
      ts,
      themeState,
      activeTab,
      switchTab,
      isAnalyzing,
      isSimulating,
      searchQuery,
      analysisKeywords,
      selectedRegion,
      selectedDimensions,
      features,
      analysisDimensions,
      regions,
      analysisStats,
      analysisResults,
      searchResults,
      simulationResults,
      searchFilters,
      simulationParams,
      simulationComplexity,
      estimatedTime,
      credibilityScore,
      startAnalysis,
      performSearch,
      startSimulation,
      exportResults
    }
  }
}
</script>

<style scoped>
/* 蓝色玻璃卡片风格 */
.glass-card {
  background: rgba(30, 64, 175, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(59, 130, 246, 0.18);
  border-radius: 16px;
}

.grid-cols-3 {
  grid-template-columns: repeat(3, 1fr);
}

.w-20 {
  width: 5rem;
  /* 图标容器宽度 */
}

.h-20 {
  height: 5rem;
  /* 图标容器高度 */
}

.w-10 {
  width: 2.5rem;
  /* 图标宽度 */
}

.h-10 {
  height: 2.5rem;
  /* 图标高度 */
}

@keyframes glow {
  from {
    text-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
  }

  to {
    text-shadow: 0 0 20px rgba(59, 130, 246, 0.8);
  }
}

.cyber-glow {
  box-shadow: 0 0 20px rgba(59, 130, 246, 0.3);
  transform: translateY(-2px);
}
</style>